<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>江汉大学智慧实验室</title>
    <link rel="stylesheet" href="css/reset.css">
</head>
<style>
    * {
        color: #fff;
    }

    .box1 {
        width: 100%;
        border: 1px solid #0efcff;
        padding: 10px 20px;
        color: #fff;
        margin-top: 2%;
        box-sizing: border-box;
        overflow: auto;
    }

    .box2 {
        width: 100%;
        padding: 10px 20px;
        border: 1px solid #0efcff;
        margin-top: 1%;
        box-sizing: border-box;
        display: flex;
        overflow: auto;
    }

    .box3 {
        width: 100%;
        padding: 10px 40px;
        border: 1px solid #0efcff;
        margin-top: 1%;
        box-sizing: border-box;
        overflow: auto;
    }

    .main {
        display: flex;
        flex-direction: column;
    }

    .box {
        height: 100%;
        flex: 1;
        overflow: auto;
    }

    .list {
        display: flex;
        align-items: center;
    }

    .item {
        width: 400px;
        height: 220px;
        /* border: solid 1px #00ff00; */
        background-image: url(./img/illness_pic.png);
        background-size: 100% 100%;
        margin-right: 20px;
        flex-shrink: 0;
    }

    .item_left {
        font-size: 18px;
        font-weight: 500;
        color: #0efcff;
        width: 100%;
        text-align: center;
        /* padding: 10px; */
        padding-bottom: 20px;
    }

    .item_content {
        display: flex;
        flex-flow: row wrap;
        justify-content: space-around;
        align-items: center;
        padding: 10px 20px;
    }

    .item_right {}

    .item_right_content {
        margin: 10px 0;
        width: 170px;
        height: 30px;
        display: flex;
        align-items: center;
    }

    .btn-bg {
        background-image: url('./img/br.png');
        display: inline-block;
        padding: 5px 10px;
    }

    .green {
        width: 15px;
        height: 15px;
        background: #00ff00;
        border-radius: 50%;
        margin-left: 10px;
        margin-right: 10px;
    }

    .red {
        width: 15px;
        height: 15px;
        background: #ff0000;
        border-radius: 50%;
        margin-left: 10px;
        margin-right: 10px;
    }

    .box2_list {
        display: flex;
    }

    .box2_item {
        width: 250px;
        height: 250px;
        padding: 0 10px;
        /* border: solid 1px #00ff00; */
        background-image: url(./img/image.png);
        background-size: 100% 100%;
        background-repeat: no-repeat;
        margin-right: 20px;
    }

    .box2_item_title {
        margin: 10px;
        font-size: 16px;
        color: #0efcff;
        margin-bottom: 0;
        padding-top: 20px;
        padding-left: 10px;
    }

    .box2_top {
        width: 100%;
        display: flex;
        flex-flow: wrap row;
        color: #0efcff;
        justify-content: space-around;
        align-items: flex-start;
    }

    .wendu {
        width: 100%;
        display: flex;
        align-items: flex-end;
        justify-content: space-between;
        margin: 10px;
    }

    .wendu div {
        text-align: left;
        margin-left: 4px;
        color: #0efcff;
    }

    .chart {
        width: 100%;
        display: flex;
        justify-content: space-around;
        margin-top: 20px;
        padding-left: 100px;
    }

    .chart_canvas {
        flex: 1;
    }
</style>

<body>
    <div class="main" id="app">
        <div class="nav">江汉大学智慧实验室</div>
        <div class="nav_btn">
            <div class="btn_left">
                <a href="./index.html">
                <div class="btn_list listActive">首页</div>
                </a>
                <a href="./index1.html">
                <div class="btn_list ">2F</div>
            </a>
            <a href="./index2.html">
                <div class="btn_list ">3F</div>
            </a>
            </div>
            <div class="btn_right">
                <div class="btn_list1">支持单位： 新天普</div>
            </div>
        </div>
        <div class="box" v-if="!loading">
            <div class="box1">
                <div class="list">
                    <div class="item" v-for="(item,index) in Object.entries(info['2F']?.First||{})" :key="index">
                        <div class="item_left">
                            {{item[0]}}
                        </div>
                        <div class="item_content">
                            <template class="item_right" v-for="(el,i) in Object.entries(item[1]||{}).sort((a, b) => {
                                const sortA = a[1].sort !== undefined ? a[1].sort : Infinity;
                                const sortB = b[1].sort !== undefined ? b[1].sort : Infinity;
                                return sortA - sortB;
                            })" :key="i">
                                <template v-if="el[1].display">
                                    <div class="item_right_content">
                                        <div v-if="typeof el[1].value == 'number'">
                                            <span class="btn-bg">{{el[0]}}</span> &nbsp; {{el[1].value}} {{el[1].unit}}
                                            &nbsp;
                                        </div>
                                        <template v-else>
                                            <span class="btn-bg">{{el[0]}}</span>
                                            <div :class="el[1].value?'green':'red'">
                                            <!-- <div>
                                                {{el[1].value?'开启':'关闭'}}
                                            </div> -->
                                        </template>
                                    </div>
                                </template>
                            </template>
                            <div class="item_right_content">
                            </div>

                        </div>

                    </div>
                </div>
            </div>
            <div class="box2">
                <div class="box2_list">
                    <div class="box2_item">
                        <div class="box2_item_title">实时温度</div>
                        <div class="box2_top">
                            <div class="wendu" v-for="(el,i) in Object.entries(info['2F']?.Second||{})" :key="i">
                                {{el[0]}}
                                <div>
                                    {{el[1]['温度'].value}} {{el[1]['温度'].unit}}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="box2_item">
                        <div class="box2_item_title">实时湿度</div>
                        <div class="box2_top">
                            <div class="wendu" v-for="(el,i) in Object.entries(info['2F']?.Second||{})" :key="i">
                                {{el[0]}}
                                <div>
                                    {{el[1]['湿度'].value}} {{el[1]['湿度'].unit}}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="box2_item">
                        <div class="box2_item_title">实时压差</div>
                        <div class="box2_top">
                            <div class="wendu" v-for="(el,i) in Object.entries(info['2F']?.Second||{})" :key="i">
                                {{el[0]}}
                                <div>
                                    {{el[1]['压差'].value}} {{el[1]['压差'].unit}}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="chart">
                    <div v-show="curIndex==0" class="chart_canvas" id="chart1"></div>
                    <div v-show="curIndex==1" class="chart_canvas" id="chart2"></div>
                    <div v-show="curIndex==2" class="chart_canvas" id="chart3"></div>
                </div>
            </div>
            <div class="box1">
                <div class="list">
                    <div class="item" v-for="(item,index) in Object.entries(info['3F']||{})" :key="index">
                        <div class="item_left">
                            {{item[0]}}
                        </div>
                        <div class="item_content">
                            <div class="item_right" v-for="(el,i) in Object.entries(item[1]||{}).sort((a, b) => {
                                const sortA = a[1].sort !== undefined ? a[1].sort : Infinity;
                                const sortB = b[1].sort !== undefined ? b[1].sort : Infinity;
                                return sortA - sortB;
                            })" :key="i">
                                <template v-if="el[1].display">
                                    <div class="item_right_content">
                                        <div v-if="typeof el[1].value == 'number'">
                                            <span class="btn-bg">{{el[0]}}</span> - {{el[1].value}} {{el[1].unit}}
                                            &nbsp;
                                        </div>
                                        <template v-else>
                                            <span class="btn-bg">{{el[0]}}</span>
                                            <div :class="el[1].value?'green':'red'"></div>
                                        </template>
                                    </div>

                                </template>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <div v-else>
            加载中...
        </div>
    </div>
</body>
<script src="./js/vue.global.js"></script>
<script src="./js/element-plus.js"></script>
<script type="text/javascript" src="./js/echarts.min.js"></script>
<script>
    const { createApp, ref, onMounted, reactive, nextTick } = Vue;
    let count = 0;
    createApp({
        setup() {


            function sortData(data) {
                console.log(222, data);

                const sortedData = {};

                for (const key in data) {
                    const obj = data[key];
                    const keys = Object.keys(obj);
                    const statusIndex = keys.indexOf('运行状态');

                    if (statusIndex !== -1) {
                        // Move '运行状态' to the first position
                        const statusObj = obj['运行状态'];
                        delete obj['运行状态'];
                        obj['运行状态'] = statusObj;
                    }

                    // Sort by 'sort' field if it exists
                    const sortedKeys = keys.sort((a, b) => {
                        const aSort = obj[a]?.sort || Infinity;
                        const bSort = obj[b]?.sort || Infinity;
                        return aSort - bSort;
                    });

                    const newObj = {};
                    sortedKeys.forEach(key => {
                        newObj[key] = obj[key];
                    });

                    sortedData[key] = newObj;
                }

                return sortedData;
            }

            // const sortedData = sortData(data);
            // console.log(sortedData);

            const info = ref({});
            const loading = ref(true);
            const data = reactive({
                temperature: {},
                humidity: {},
                pressure: {},
            });
            const charts = ref({});
            const colorMap = {}; // 存储房间对应的颜色
            const timePoints = ref([]);
            const curIndex = ref(0)

            onMounted(async () => {
                const fetchData = async () => {
                    try {
                        const res = await fetch('http://127.0.0.1:5000/data')
                            .then(res => res.json());
                        info.value = res;
                        count++;
                        updateData(res['2F'].Second);
                    } catch (error) {
                        console.error('Failed to fetch data:', error);
                    } finally {
                        loading.value = false;
                    }
                };

                fetchData();
                setInterval(fetchData, 1000);
                setInterval(() => {
                    nextTick(() => {
                        let index = curIndex.value
                        index++
                        if (index > 2) {
                            index = 0
                        } 
                        curIndex.value = index
                        setTimeout(() => {
                            const selector = `#chart${curIndex.value+1}`;
                        const chart = charts.value[selector];
                        console.log(11111, chart,selector,document.querySelector(selector));
                        chart?.resize();
                        }, 200);
                    })
                }, 20000)
            });

            const updateData = (secondData) => {
                // 更新每个房间的数据
                Object.keys(secondData).forEach((room) => {
                    const roomTemp = secondData[room]['温度'].value;
                    const roomHum = secondData[room]['湿度'].value;
                    const roomPre = secondData[room]['压差'].value;

                    // 确保每个房间都有对应的数组用于存储数据
                    if (!data.temperature[room]) {
                        data.temperature[room] = [];
                        data.humidity[room] = [];
                        data.pressure[room] = [];
                    }

                    // 添加新数据点到每个房间的数组中
                    data.temperature[room].push(roomTemp);
                    data.humidity[room].push(roomHum);
                    data.pressure[room].push(roomPre);

                    // 如果数据点超过100个，则移除最早的数据点
                    if (data.temperature[room].length > 100) {
                        data.temperature[room].shift();
                        data.humidity[room].shift();
                        data.pressure[room].shift();
                    }
                });
                if (count <= 100) {

                    timePoints.value = new Array(count).fill(0).map((_, index) => index);
                } else {
                    let arr = []
                    for (let index = count - 100; index <= count; index++) {
                        arr.push(index)
                    }
                    timePoints.value = arr
                }


                // 更新图表
                initCharts();
            };

            const initCharts = () => {
                const types = ['temperature', 'humidity', 'pressure'];
                types.forEach((type, index) => {
                    const selector = `#chart${index + 1}`;
                    if (!charts.value[selector]) {
                        if(!document.querySelector(selector))return
                        charts.value[selector] = echarts.init(document.querySelector(selector), null, {
                            renderer: 'canvas',
                            useDirtyRect: false
                        });
                    }
                    const chart = charts.value[selector];
                    const option = {
                        legend:{
                            data:Object.keys(info.value['2F'].Second).map(item=>item),
                            textStyle: {
                                color: '#fff'
                            },
                            right:0,
                            // orient: 'vertical',
        x:'left',      //可设定图例在左、右、居中
        y:'top',     //可设定图例在上、下、居中
                        },
                        title: {
                            text: type === 'temperature' ? '历史温度曲线' : type === 'humidity' ? '历史湿度曲线' : '历史压差曲线',
                            textStyle: {
                                color: '#fff'
                            },
                             left: 'right',
                             top:"20px"
                        },
                        // tooltip: {
                        //     trigger: 'axis',
                        //     axisPointer: {
                        //         type: 'cross'
                        //     },
                        //     formatter: function (params) {
                        //         const room = params[0].seriesName;
                        //         const value = params[0].value;
                        //         return `${room}: ${value[1]}`;
                        //     }
                        // },
                        xAxis: {
                            type: 'category',
                            data: timePoints.value.map(t => `${t}s`),
                            axisLine: {
                                lineStyle: {
                                    color: '#fff'
                                }
                            },
                            axisLabel: {
                                textStyle: {
                                    color: '#fff'
                                }
                            }
                        },
                        yAxis: {
                            type: 'value',
                            axisLine: {
                                lineStyle: {
                                    color: '#fff'
                                }
                            },
                            axisLabel: {
                                textStyle: {
                                    color: '#fff'
                                }
                            }
                        },
                        series: Object.keys(info.value['2F'].Second).map(room => {
                            const color = colorMap[room] || getRandomColor();
                            colorMap[room] = color;
                            console.log(1111,room);
                            
                            return {
                                name: room,
                                type: 'line',
                                data: data[type][room] || [],
                                lineStyle: {
                                    color: color
                                },
                                itemStyle: {
                                    color: color
                                }
                            };
                        })
                    };
                    chart.setOption(option);
                });
            };

            const getRandomColor = () => {
                const letters = '0123456789ABCDEF';
                let color = '#';
                for (let i = 0; i < 6; i++) {
                    color += letters[Math.floor(Math.random() * 16)];
                }
                return color;
            };

            return {
                info,
                loading,
                curIndex,
                sortData
            };
        }
    }).use(ElementPlus).mount('#app');
</script>

</html>